﻿CREATE PROCEDURE [dbo].[spMarkPackageShipped]
	@PackageID int 
AS
	set nocount on
	if ( select top 1 OrderStatusCode from tblOrderHeader T1
			join tblInventoryTransaction T2 on T1.OrderID = T2.OrderID
		where T2.PackageID = @PackageID ) <> 'O'
		raiserror ( 'Attempt to flag an order that is not in-process as shipped', 16, 1 )

	-- Mark the inventory transactions as committed
	update tblInventoryTransaction set InventoryTransactionStatusCode = 'C' where PackageID = @PackageID

	-- Set the ShippedDate on the package
	update tblPackage set ShippedDate = GETDATE() where PackageID = @PackageID

	-- Set the order status code to Shipped.
	update T2 set OrderStatusCode = 'S'
	from tblInventoryTransaction T1
		join tblOrderHeader T2 on T1.OrderID = T2.OrderID
	where T1.PackageID = @PackageID

	declare @CustomerID int
	select top 1 @CustomerID = CustomerID
	from tblOrderHeader T1
		join tblInventoryTransaction T2 on T1.OrderID = T2.OrderID
	where T2.PackageID = @PackageID

	exec spBuildSearchKeys @CustomerID

RETURN 0